<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建场景"
    :width="700"
    :append-to-body="false"
    @close="handleClose"
    custom-class="center-detail"
  >
    <JLForm
      ref="formRef"
      :form-config="formConfig"
      :form-data="formData"
      :form-item-config="formItemConfig"
    >
      <template #slotAddress>
        <div class="map-address-wrap">
          <el-select
            v-model="mapSearchKey"
            filterable
            remote
            reserve-keyword
            placeholder="请输入地址"
            :remote-method="remoteMethod"
            :loading="mapSearchLoading"
            @change="addressChange"
          >
            <el-option
              v-for="item in mapSearchOptions"
              :key="item.hotPointID"
              :label="item.name"
              :value="item.hotPointID"
            />
          </el-select>
          <div class="jw-text">经度/维度：{{ lnglat.lng }}/{{ lnglat.lat }}</div>
          <div class="jw-tip">定位说明:如无法根据详细地址找到定位,请在地图上手动点击进行定位。</div>
          <div class="map-wrap">
            <div id="map-container"></div>
            <div class="map-toolbar">
              <div class="map-direction">
                <SvgIcon
                  class="map-direction-top"
                  icon-class="down"
                  @click="onMapDirection('top')"
                />
                <SvgIcon
                  class="map-direction-right"
                  icon-class="down"
                  @click="onMapDirection('right')"
                />
                <SvgIcon
                  class="map-direction-bottom"
                  icon-class="down"
                  @click="onMapDirection('bottom')"
                />
                <SvgIcon
                  class="map-direction-left"
                  icon-class="down"
                  @click="onMapDirection('left')"
                />
              </div>
              <div
                class="map-grow"
                :class="{ disabled: currZoom > 17 }"
                @click="onGrowShrink('grow')"
              >
                <img src="@/assets/png/+.png" alt="" />
              </div>
              <div
                class="map-shrink"
                :class="{ disabled: currZoom < 2 }"
                @click="onGrowShrink('shrink')"
              >
                <img src="@/assets/png/-.png" alt="" />
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #slotResUrl>
        <el-upload
          action="#"
          class="upload-res-file"
          :limit="1"
          drag
          accept=".json"
          :show-file-list="false"
          :before-upload="beforeUpload"
        >
          <template #default>
            <div class="up-load-res-file">
              <SvgIcon icon-class="ic_shangchuan" />
              <div class="el-upload__text">将文件拖到这里，或点击上传</div>
              <div class="el-upload__tip">支持上传预置场景JSON文件</div>
            </div>
          </template>
        </el-upload>
        <div class="large-file" v-if="jsonFileName">
          <SvgIcon icon-class="ic_file"> </SvgIcon>
          {{ jsonFileName }}
          <SvgIcon class="close-icon" icon-class="ic_close" @click="removeFile"> </SvgIcon>
        </div>
      </template>
    </JLForm>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button color="#0560FD" type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { create } from './composables/create';
import { JLForm } from '@jl/element-plus';
import { ElMessage } from 'element-plus';
import { createScene } from '@/api/scene';
import { commonUpload, tdtSearch, tdtGeocoderSearch } from '@/api/common';
import { CommonUploadResp } from '@/api/common/types';
import AMapLoader from '@amap/amap-jsapi-loader';
import { messageUtil } from '@jl/element-plus/utils';

const { formRef, formConfig, formData, formItemConfig, proListRun, validateRotateNumber } =
  create();
const dialogVisible = ref<boolean>(true);
const emit = defineEmits(['closeHandle']);
const jsonFileName = ref<string>('');
const AMapIns = null as any;
let map = null as any;
let geocoder = null as any;
const currZoom = ref<number>(15);
const lnglat = ref<any>({
  lng: '-',
  lat: '-',
});
const mapSearchKey = ref<string>('');
const mapSearchOptions = ref<any[]>([]);
const mapSearchLoading = ref<boolean>(false);
const handleClose = () => {
  emit('closeHandle', false);
};

const beforeUpload = async (file: any) => {
  if (!(file.name && file.name.endsWith('.json'))) {
    ElMessage.warning('请上传 .json 格式的文件');
    return false;
  }
  const filemaxsize = 1024 * 1024 * 10;
  if (file.size > filemaxsize) {
    ElMessage.warning('请上传10兆以内的文件');
    return false;
  }
  const res: CommonUploadResp = await commonUpload(file);

  formData.value.resUrl = res.files[0].configJsonId;
  jsonFileName.value = file.name;

  !formItemConfig.value.filter((v) => v.key === 'xRotate').length &&
    formItemConfig.value.push(
      {
        type: 'input',
        key: 'xRotate',
        label: 'X轴旋转',
        placeholder: '',
        span: 8,
        rules: [
          {
            required: true,
            validator: validateRotateNumber,
          },
        ],
      },
      {
        type: 'input',
        key: 'yRotate',
        label: 'Y轴旋转',
        placeholder: '',
        span: 8,
        rules: [
          {
            required: true,
            validator: validateRotateNumber,
          },
        ],
      },
      {
        type: 'input',
        key: 'zRotate',
        label: 'Z轴旋转',
        placeholder: '',
        span: 8,
        rules: [
          {
            required: true,
            validator: validateRotateNumber,
          },
        ],
      }
    );
  return false;
};

onMounted(() => {
  proListRun({
    params: {
      index: 1,
      pageSize: 1000,
      blurStr: '',
      state: -1,
    },
  });
  nextTick(() => {
    initMap();
  });
});

function initMap() {
  const { T } = window;
  map = new T.Map('map-container', {
    projection: 'EPSG:4326',
  });
  map.centerAndZoom(new T.LngLat(116.397428, 39.90923), 15);
  map.on('click', (e: any) => {
    lnglat.value.lng = e.lnglat.lng;
    lnglat.value.lat = e.lnglat.lat;
    tdtGeocoderSearch({ lon: e.lnglat.lng, lat: e.lnglat.lat }).then((res: any) => {
      const {
        data: { status, result },
      } = res;
      if (res.status === 200 && status === '0') {
        mapSearchOptions.value = [
          {
            name: result.addressComponent.address,
            hotPointID: '1',
            lonlat: `${result.location.lon},${result.location.lat}`,
          },
        ];
        mapSearchKey.value = result.addressComponent.address;
      }
    });
  });
  geocoder = new T.Geocoder();
}

function submit() {
  formRef.value?.getInstance().validate((valid, fields) => {
    if (valid) {
      // if (!lnglat.value.lng || !lnglat.value.lat) {
      //   messageUtil.warning('请选择场景地址');
      //   return;
      // }
      const fData = new FormData();
      fData.set('activityName', formData.value.fileResName);
      fData.set('projectId', formData.value.projectId);
      fData.set('actDesp', formData.value.matDesp);
      fData.set('actCover', '');
      fData.set('actViewAngle', '');
      fData.set('conifgId', formData.value.resUrl);
      fData.set('longitude', lnglat.value.lng === '-' ? '' : lnglat.value.lng);
      fData.set('latitude', lnglat.value.lat === '-' ? '' : lnglat.value.lat);
      fData.set('xRotate', formData.value.xRotate);
      fData.set('yRotate', formData.value.yRotate);
      fData.set('zRotate', formData.value.zRotate);
      const param = {
        data: fData,
      };
      createScene(param).then((res: API.Scene.CreateSceneResp) => {
        emit('closeHandle', true);
      });
    }
  });
}

function removeFile() {
  formData.value.resUrl = '';
  jsonFileName.value = '';
  for (let i = formItemConfig.value.length - 1; i >= 0; i--) {
    if (['xRotate', 'yRotate', 'zRotate'].includes(formItemConfig.value[i].key)) {
      formItemConfig.value.splice(i, 1);
    }
  }
  formData.value.xRotate = '';
  formData.value.yRotate = '';
  formData.value.zRotate = '';
}

function remoteMethod(query: string) {
  if (query) {
    tdtSearch({ keyWord: query }).then((res: any) => {
      const {
        status,
        data: { pois },
      } = res;
      if (status === 200) {
        mapSearchOptions.value = pois || [];
      }
    });
  } else {
    mapSearchOptions.value = [];
  }
}

function addressChange(id: string) {
  const { T } = window;
  const targetAddress = mapSearchOptions.value.filter((v) => v.hotPointID === id);
  if (!targetAddress.length) return;
  const location = targetAddress[0].lonlat.split(',');
  lnglat.value.lng = location[0];
  lnglat.value.lat = location[1];
  map.centerAndZoom(new T.LngLat(Number(location[0]), Number(location[1])), 18);
  currZoom.value = 18;
}

function onMapDirection(dir: string) {
  const { T } = window;
  if (dir === 'top') {
    map.panBy(new T.Point(0, 50));
    return;
  }
  if (dir === 'bottom') {
    map.panBy(new T.Point(0, -50));
    return;
  }
  if (dir === 'left') {
    map.panBy(new T.Point(50, 0));
    return;
  }
  if (dir === 'right') {
    map.panBy(new T.Point(-50, 0));
  }
}

function onGrowShrink(str: string) {
  const zoom = map.getZoom();
  if (str === 'grow') {
    if (zoom < 18) {
      map.setZoom(zoom + 1);
      currZoom.value = zoom + 1;
    }
    return;
  }
  if (zoom > 1) {
    map.setZoom(zoom - 1);
    currZoom.value = zoom - 1;
  }
}
</script>

<style lang="less" scoped>
:deep(.el-textarea__inner) {
  height: 96px;
}
.file-type-select {
  //todo
  // .el-select-dropdown__item {
  //   height: 64px;
  // }
}
.upload-res-file {
  width: 100%;
  :deep(.el-upload) {
    width: 100%;
    &-dragger {
      border: none;
      padding: 0px;
    }
  }
}
.large-file {
  width: 100%;
  display: flex;
  align-items: center;
  .svg-icon {
    font-size: 20px;
    margin-right: 6px;
  }
  .close-icon {
    margin-left: auto;
    margin-right: 0px;
    cursor: pointer;
  }
}
.up-load-res-file {
  height: 148px;
  flex: 1;
  border-radius: 8px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  display: flex;
  border: 1px solid #e8e8e8;
  .svg-icon {
    font-size: 48px;
  }
  .el-upload__text {
    color: #585858;
    font-weight: 600;
    font-size: 16px;
  }
  .el-upload__tip {
    font-size: 14px;
    color: #9a9a9a;
  }
}
.cover-up-icon {
  width: 118px;
  height: 118px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e8e8e8;
  .svg-icon {
    font-size: 48px;
  }
}
.avatar {
  width: 118px;
  height: 118px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.map-address-wrap {
  width: 100%;
  color: #585858;
  line-height: initial;
  .jw-tip {
    font-weight: 400;
    margin: 10px 0;
  }
  .jw-text {
    font-weight: 500;
    margin-top: 10px;
  }
  .map-wrap {
    position: relative;
    .map-toolbar {
      position: absolute;
      top: 12px;
      right: 4px;
      width: 52px;
      height: 104px;
      background: fade(#1f2329, 42%);
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      z-index: 1050;
      .map-direction {
        position: relative;
        width: 36px;
        height: 36px;
        background: #fff;
        border-radius: 50%;
        margin-bottom: 8px;
        .svg-icon {
          position: absolute;
          font-size: 15px;
          cursor: pointer;
        }
        &-top {
          top: 0;
          left: 50%;
          transform: translateX(-50%) rotate(180deg);
        }
        &-right {
          top: 50%;
          right: 0;
          transform: translateY(-50%) rotate(-90deg);
        }
        &-bottom {
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
        }
        &-left {
          top: 50%;
          left: 0;
          transform: translateY(-50%) rotate(90deg);
        }
      }
      .map-grow,
      .map-shrink {
        height: 16px;
        border-radius: 1px;
        background: #fff;
        cursor: pointer;
        img {
          width: 16px;
        }
        &.disabled {
          cursor: no-drop;
          opacity: 0.6;
        }
      }
      .map-grow {
        margin-bottom: 8px;
      }
    }
  }
  :deep(#map-container) {
    height: 120px;
    .tdt-control-copyright {
      margin-bottom: -50px;
    }
  }
}
</style>
